package ai.zixing.pool;

import ai.zixing.config.ThreadPoolConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author zixing
 */
@Configuration
@EnableAsync
public class CustomizeThreadPool {

    @Resource
    private ThreadPoolConfig config;

    @Bean("customizeThreadPoolBean")
    public Executor getThreadPoolBean() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(config.getCorePoolSize());
        // 和 ai.zixing.pool.MyDefinedThreadPool.getAsyncExecutor 基本一致
        executor.setMaxPoolSize(config.getMaxPoolSize());
        executor.setQueueCapacity(config.getQueueCapacity());
        executor.setKeepAliveSeconds(config.getKeepAliveSeconds());
//        executor.setThreadNamePrefix(config.getThreadNamePrefix());
        executor.setThreadNamePrefix("customizeThreadPoolBean-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 不是作为Bean的时候，需要自己手动去调用initialize()方法 不然报错
        // 参考 https://blog.csdn.net/qq_41055045/article/details/115032009
        // 可以不执行 executor.initialize(); 注入 spring 中 spring 会对该线程池初始化
//        executor.initialize();
        return executor;
    }
}
